package com.bolt.common.collection;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class CaseInsensitiveLinkedMap<K, V> extends LinkedHashMap<K, V> {
    /**
     *
     */
    private static final long serialVersionUID = 391326207592902507L;

    /**
     * /**
     * 将Key转为小写
     *
     * @param key KEY
     * @return 小写KEy
     */
    private static Object lowerCaseKey(Object key) {
        if (key instanceof CharSequence) {
            key = key.toString().toLowerCase();
        }
        return key;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.util.LinkedHashMap#get(java.lang.Object)
     */
    @Override
    public V get(Object key) {
        return super.get(lowerCaseKey(key));
    }

    /*
     * (non-Javadoc)
     *
     * @see java.util.HashMap#put(java.lang.Object, java.lang.Object)
     */
    @Override
    public V put(K key, V value) {
        return super.put((K) lowerCaseKey(key), value);
    }

    /*
     * (non-Javadoc)
     *
     * @see java.util.HashMap#putAll(java.util.Map)
     */
    @Override
    public void putAll(Map<? extends K, ? extends V> map) {
        if (map == null || map.isEmpty())
            return;
        Iterator<?> iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<K, V> entry = (Map.Entry<K, V>) iter.next();
            super.put((K) lowerCaseKey(entry.getKey()), entry.getValue());
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see java.util.HashMap#remove(java.lang.Object)
     */
    @Override
    public V remove(Object key) {
        return super.remove(lowerCaseKey(key));
    }

    /*
     * (non-Javadoc)
     *
     * @see java.util.HashMap#putIfAbsent(java.lang.Object, java.lang.Object)
     */
    @Override
    public V putIfAbsent(K key, V value) {
        return super.putIfAbsent((K) lowerCaseKey(key), value);
    }

    /*
     * (non-Javadoc)
     *
     * @see java.util.HashMap#replace(java.lang.Object, java.lang.Object,
     * java.lang.Object)
     */
    @Override
    public boolean replace(K key, V value1, V value2) {
        return super.replace((K) lowerCaseKey(key), value1, value2);
    }

    /*
     * (non-Javadoc)
     *
     * @see java.util.HashMap#replace(java.lang.Object, java.lang.Object)
     */
    @Override
    public V replace(K key, V value) {
        return super.replace((K) lowerCaseKey(key), value);
    }

    /*
     * (non-Javadoc)
     *
     * @see java.util.HashMap#containsKey(java.lang.Object)
     */
    @Override
    public boolean containsKey(Object key) {
        return super.containsKey(lowerCaseKey(key));
    }
}
